package com.wangmei.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wangmei.model.Attributevalue;
import com.wangmei.model.Product;
import com.wangmei.model.Productkuid;
import com.wangmei.model.Productpic;
import com.wangmei.pojo.*;
import com.wangmei.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import unitTool.Dictionary;
import unitTool.JsonRsp;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/product")
public class ProductController {
    private final Logger logger = LoggerFactory.getLogger(ProductController.class);
    @Autowired
    private ProductPicService productPicService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductkuidService productkuidService;
    @Autowired
    private CategeryService categeryService;
    @Autowired
    private AttributeService attributeService;

    /**
     * 根据pid查询某个商品的信息
     */
    @RequestMapping(value = "/getProduct",method = RequestMethod.GET)
    public JsonRsp getProductByPid(@RequestParam("pid")int pid){
        return JsonRsp.success(productService.getProductByPid(pid));
    }

    /**
     * 获取所有的商品信息,包含模糊查詢
     */
    @RequestMapping(value = "/getAllProduct",method = RequestMethod.GET)
    public JsonRsp getAllProduct(@RequestParam(value = "pageIndex",defaultValue = Dictionary.PageDirect.PAGE_INDEX) int pageIndex,
                                 @RequestParam(value = "pageSize",defaultValue = Dictionary.PageDirect.PAGE_SIZE)int pageSize,
                                 @RequestParam(value = "search")String search) throws UnsupportedEncodingException {
        PageHelper.startPage(pageIndex,pageSize);
        List<Product> productList;
        String s = search;
        if (s.isEmpty()){
            productList = productService.getProductList();
        }else{
            productList = productService.getProductByPname(s);
        }
        PageInfo pageInfo = new PageInfo(productList);
        return JsonRsp.success(pageInfo.getList()).setTotal(pageInfo.getTotal());
    }

    /**
     * 通过分类名cname 获取该分类下的所有商品的信息，库存
     * @param cname
     * @return
     */
    @RequestMapping(value = "/getProductkuidAndPicByCname",method = RequestMethod.GET)
    public JsonRsp getProductkuidAndPicByCname(@RequestParam("cname")String cname, HttpSession session){
        List<Integer> cidList = categeryService.getCidAndChildcidByCname(cname);
        List<ProductAndkuidPojo> pakpList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        //获得当前用户
        UserSimplify userSimplify = (UserSimplify) session.getAttribute(Dictionary.SessionKey.CURRENT_USER);
        if (null != userSimplify)
            map.put("uid",userSimplify.getUid());//如果存在用户查询喜好

        for (int cid : cidList){
//            System.out.println(cid);
            map.put("cid",cid);
            List<ProductCollection> productList = productService.getProductByCid(map);
            for (ProductCollection p : productList){
                ProductAndkuidPojo pakp = new ProductAndkuidPojo();
                int storenum = productkuidService.getProductStoreByPid(p.getPid());
                pakp.setProduct(p);
                pakp.setStorenum(storenum);
                pakp.setIsCollect(p.getIsCollect());
                pakpList.add(pakp);
            }
        }
        return JsonRsp.success(pakpList);
    }

    /**
     * 分页----通过分类名cname 获取该分类下的所有商品的信息，库存
     * @param cname
     * @return
     */
    /*@RequestMapping(value = "/getProductAndKuidByCname",method = RequestMethod.GET)
    public JsonRsp getProductAndKuidByCname(@RequestParam(value = "pageIndex",defaultValue = "1")int pageIndex,
                                               @RequestParam(value = "pageSize",defaultValue = "10")int pageSize,
                                               @RequestParam("cname")String cname){
        PageHelper.startPage(pageIndex,pageSize);
        List<Integer> cidList = categeryService.getCidAndChildcidByCname(cname);
        for (int i : cidList){
            System.out.println(i);
        }
        List<ProductAndkuidPojo> pakpList = new ArrayList<>();
        for (int cid : cidList){
            System.out.println(cid);
            List<Product> productList = productService.getProductByCid(cid);
            for (Product p : productList){
                ProductAndkuidPojo pakp = new ProductAndkuidPojo();
                int storenum = productkuidService.getProductStoreByPid(p.getPid());
                pakp.setProduct(p);
                pakp.setStorenum(storenum);
                pakpList.add(pakp);
            }
        }
        PageInfo pageInfo = new PageInfo(pakpList);
        return JsonRsp.success(pageInfo).setTotal(pageInfo.getTotal());
    }*/

    /**
     * 分页---模糊查询商品信息与库存
     * @param pageIndex
     * @param pageSize
     * @param search
     * @return
     */
    @RequestMapping(value = "/getProductAndKuidByPname",method = RequestMethod.GET)
    public JsonRsp getProductAndKuidByPname(@RequestParam(value = "pageIndex",defaultValue = "1")int pageIndex,
                                            @RequestParam(value = "pageSize", defaultValue = "10")int pageSize,
                                            @RequestParam(value = "search")String search){
        PageHelper.startPage(pageIndex,pageSize);
        List<ProductAndkuidPojo> papList = new ArrayList<>();
        List<Product> productList;
        if (search.isEmpty()){
            productList = productService.getProductList();
        }else{
            productList = productService.getProductByPname(search);
        }
        for (Product p : productList){
            ProductAndkuidPojo pakp = new ProductAndkuidPojo();
            pakp.setProduct(p);
            pakp.setStorenum(productkuidService.getProductStoreByPid(p.getPid()));
            papList.add(pakp);
        }
        PageInfo pageInfo = new PageInfo(papList);
        return JsonRsp.success(pageInfo.getList()).setTotal(pageInfo.getTotal());
    }

    /**
     * 分类----子类找父类
     * @param cid
     * @return
     */
    @RequestMapping(value = "/getParentCategeryByCidPid", method = RequestMethod.GET)
    public JsonRsp getParentCategeryByCid(@RequestParam("cid")int cid,
                                          @RequestParam("pid")int pid){
        Product product = productService.getProductByPid(pid);
        String pname = product.getPname();
        List<String> cList = new ArrayList<>();
        cList.add(pname);
        List<String> cnameList = categeryService.getCnameAndParentcnameByCid(cid);
        for (String s : cnameList){
            cList.add(s);
        }
        return JsonRsp.success(cList);
    }

    /**
     * 通过pid,cid获取商品属性、属性值以及总库存
     * @param pid
     * @param cid
     * @return
     */
    @RequestMapping(value = "/getKuidAndAttAndAttvalueByPidCid",method = RequestMethod.GET)
    public JsonRsp getKuidAndAttAndAttvalueByPidCid(@RequestParam(value = "pid")int pid,
                                                    @RequestParam(value = "cid")int cid){
        KuidAndAttPojo kaap = new KuidAndAttPojo();
        int totalStore = productkuidService.getProductStoreByPid(pid);
        AttributePojo a = attributeService.getAttributePojoByCid(cid);
        kaap.setTotalstore(totalStore);
        kaap.setAname(a.getAname());
        kaap.setAid(a.getAid());
        List<String> vnameList = new ArrayList<>();
        for (Attributevalue av : a.getAttributevalueList()){
            vnameList.add(av.getVname());
        }
        kaap.setVname(vnameList);
        return JsonRsp.success(kaap);
    }



    /**
     * 新增一个商品
     */
    @RequestMapping(value = "/addProduct",method = RequestMethod.POST)
    public JsonRsp addProduct(@RequestBody Product product){
        if (productService.addProduct(product)>0){
            return JsonRsp.success("","success");
        }else{
            return JsonRsp.fail(400,"fail");
        }
    }

    /**
     * 修改商品信息
     */
    @RequestMapping(value = "/updateProduct",method = RequestMethod.POST)
    public JsonRsp updateProduct(@RequestBody Product product){
        logger.info(product.getPname());
        if (productService.updateProduct(product)>0){
            return JsonRsp.success("","success");
        }else{
            return JsonRsp.fail(400,"fail");
        }
    }

    /**
     * 删除某个商品
     */
    @RequestMapping(value = "/deleteProduct",method = RequestMethod.GET)
    public JsonRsp deleteProduct(@RequestParam(value = "pid") int pid){
        if (productService.deleteProduct(pid) > 0){
            return JsonRsp.success("","success");
        }else{
            return JsonRsp.fail(400,"fail");
        }
    }

    /**
     * 删除多个商品记录
     */
    @RequestMapping(value = "/deleteProducts",method = RequestMethod.GET)
    public JsonRsp deleteProductList(@RequestParam(value = "pids")List<Integer> pids){
        if (productService.deleteProducts(pids)>0){
            return JsonRsp.success("","success");
        }else{
            return JsonRsp.fail(400,"fail");
        }
    }

    /**
     * 获取该商品的总库存
     */
    @RequestMapping(value = "/getAllStoreByPid",method = RequestMethod.GET)
    public JsonRsp getAllStore(@RequestParam("pid")int pid){
        return JsonRsp.success(productkuidService.getProductStoreByPid(pid));
    }

    /**
     * 获取某商品的某个类别的库存
     */
    @RequestMapping(value = "/getStoreByPidVid",method = RequestMethod.GET)
    public JsonRsp getStoreByPidVid(@RequestParam("pid")int pid,@RequestParam("vid")int vid){
        return JsonRsp.success(productkuidService.getProductStoreByPidVid(pid,vid));
    }

    /**
     * 通过vname和pid,aid获取库存
     * @param pid
     * @param vname
     * @return
     */
    @RequestMapping(value = "/getStoreByPidVnameAid",method = RequestMethod.GET)
    public JsonRsp getStoreByPidVname(@RequestParam("pid")int pid,
                                      @RequestParam("vname")String vname,
                                      @RequestParam("aid")int aid){
        int vid = attributeService.getVidByVnameAid(vname,aid);
        Productkuid productkuid = productkuidService.getProductStoreByPidVid(pid, vid);
        return JsonRsp.success(productkuid);
    }

    /**
     * 根据pid查询某个商品的主图片
     */
    @RequestMapping(value = "/getProPic",method = RequestMethod.GET)
    public JsonRsp getpic(@RequestParam("pid") int pid){
        Product product = productService.getProductByPid(pid);
        String imgurl = product.getImgurl();
        return JsonRsp.success(imgurl);
    }

    /**
     * 根据pid查询某个商品的全部图片
     */
    @RequestMapping(value = "/getAllPic",method = RequestMethod.GET)
    public JsonRsp getAllPic(@RequestParam("pid") int pid){
        return JsonRsp.success(productPicService.getProductAllPic(pid));
    }

    /**
     * 根据pid,拼接product和productpic
     * @param pid
     * @return
     */
    @RequestMapping(value = "/getAllPicAndMainPicBypid",method = RequestMethod.GET)
    public JsonRsp getAllpicAndMainpic(@RequestParam("pid")int pid){
        Product product = productService.getProductByPid(pid);
        ProductAndPicPojo papp = new ProductAndPicPojo();
        papp.setProduct(product);
        List<Productpic> productpicList = productPicService.getProductAllPic(pid);
        papp.setProductpicList(productpicList);
        return JsonRsp.success(papp);
    }


    @RequestMapping("/getpics")
    public JsonRsp getAllPic(){
        return JsonRsp.success(createpic(productPicService.getPics()));
    }
    private List<Map<String,Object>> createpic(List<ProductPicPojo>list){
        Map<Integer,Map<String,Object>> dic = new HashMap<>();
        List<Map<String,Object>> relist=new ArrayList<>();
        for(ProductPicPojo d:list) {
            Map<String,Object>item =  dic.get(d.getPid());
           if(item == null){
             item = new HashMap<>();
             item.put("pid",d.getPid());
             item.put("name",d.getName());
             item.put("url",d.getUrl());
             List<String> url = new ArrayList<>();
             url.add(d.getPicurl());
             item.put("urls",url);

             dic.put(d.getPid(),item);
             relist.add(item);
           }else{
               List<String> url = (List<String>) item.get("urls");
               url.add(d.getPicurl());
           }
        }
        return relist;
    }

    @RequestMapping("/inserpics")
    public JsonRsp insertPics(@RequestParam(value = "pid")int pid,
                             @RequestParam(value = "urls[]") String[] urls){
        try{
            List<String> urllist = new ArrayList<>();
            for(int i = 0;i<urls.length;i++)
                urllist.add(urls[i]);
            return JsonRsp.success(productPicService.insertList(pid,urllist));
        }catch (Exception e){
            e.printStackTrace();
            return JsonRsp.fail(100,"内部错误");
        }
    }
    @RequestMapping("/inserpic")
    public JsonRsp insertPic(@RequestBody Productpic productpic){
        try{
            return JsonRsp.success(productPicService.insert(productpic));
        }catch (Exception e){
            e.printStackTrace();
            return JsonRsp.fail(100,"内部错误");
        }

    }

}
